var iconv = require('iconv-lite');
var db = require('./db.js');
var moment  = require('moment');

var content = "";
var res = {};

var hexToStr = function (hex){
    var hexByte=[];
    for(var i = 0; i < hex.length; i = i + 2) {
        var curCharCode = parseInt(hex.substr(i, 2), 16); // ASCII Code Value
        hexByte.push(curCharCode);
    }
    var buffer = new Buffer(hexByte);
    var buf_str = buffer.toString();

    return buf_str;
}

var parseUploadMessage = function (msg) {
    var msgByte = msg.split(",");
    var msgContent = msgByte[5].split("*")[0];
    if(msgByte[0] == 'BDTXR'){ //判断是什么信息，$BDTXR北斗短报文
        res.sender = msgByte[2]; //北斗卡号
        var type = msgByte[3]; //信息类别
        if(type == "0"){  //汉字
            content = msgContent;
        }else if(type == "1"){ // 代码
            content = msgContent;
        } else if(type == "2"){ //混合
            content = hexToStr(msgContent.substr(2, msgContent.length));
            //console.log(content);
            var contentArray = content.split(",");
            if(contentArray.length < 6){
                res.time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
                res.content = content;
                db.uploadMessage.create(res);
            }else {
                res.lon = contentArray[0]; //经度
                res.lat = contentArray[2]; //纬度
                res.time = contentArray[4]; //时间
                res.alarm = contentArray[5]; //报警状态
                //console.log(res);
                db.uploadLocation.create(res);
            }
        }
    }

    return "$BDPOS,"+ res.sender + "," + content + "*";  //北斗卡号+经纬度+时间+状态
}

//parseUploadMessage('$BDTXR,1,0294668,2,,A43132332E3730353931387C33302E3436343932387C317C323031372D30332D30312031343A33303A3237*43');

module.exports = {
    parseUploadMessage: parseUploadMessage
}




//var str = iconv.decode(buf, 'GBK'); //return unicode string from GBK encoded bytes

//var buf = iconv.encode(str, 'GBK');//return GBK encoded bytes from unicode string